/*
EP3D is a real-time 3D planet engine , which in addition to providing 
substandard scene rendering and scene management, of course, it also 
provides some basic class libraries to build the entire virtual 
planet, or even the entire universe.

Copyright (C) 2010  Hongjiang zhang	(zhjwyat@gmail.com)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "EP3DFileSystem.h"
#include "EP3DMemory.h"
#include "EP3DFileStream.h"
#include "EP3DString.h"
#include "EP3DXMLStream.h"
#include "EP3DMath.h"

namespace EP3D
{
	IStream* FileSystem::CreateFileReader(const TCHAR* pszFilename)
	{
#pragma warning(push)
#pragma warning(disable : 4996)
		FILE* pfFile = _tfopen(pszFilename, TEXT("rb"));
#pragma warning(pop)
		if (!pfFile) {
			LogError(TEXT("failed to read file: %s"), pszFilename);
			return NULL;
		}

		fseek(pfFile, 0, SEEK_END);
		return EP3DNew FileReader(pfFile, ftell(pfFile));
	}


	OStream* FileSystem::CreateFileWriter(const TCHAR* pszFilename, bool bAppend)
	{
		const TCHAR* mode = bAppend ? TEXT("ab") : TEXT("wb");
#pragma warning(push)
#pragma warning (disable : 4996)
		FILE* pfFile = _tfopen(pszFilename, mode);
#pragma warning(pop)
		if (!pfFile) {
			LogError(TEXT("failed to write file: %s"), pszFilename);
			return NULL;
		}

		return EP3DNew FileWriter(pfFile);
	}

	int FileSystem::GetFileSize(const TCHAR* pszFilename)
	{
		IStream* pkIStream = CreateFileReader(pszFilename);
		if (!pkIStream)
			return -1;

		int nResult = pkIStream->GetSize();
		EP3DDelete pkIStream;
		return nResult;
	}

	bool FileSystem::IsReadOnly(const TCHAR* pszFilename)
	{
		if (GetFileSize(pszFilename) < 0)
			return false;

		return (_taccess(pszFilename, 4) == 0);
	}

	FileSystem::CopyResult FileSystem::Copy(const TCHAR* pszDest, const TCHAR* pszSrc, IProgress* pkProgress)
	{
		if (pkProgress && !pkProgress->Poll(0.0f))
			return COPY_CANCEL;

		CopyResult eResult = COPY_OK;
		String srcFile = pszSrc;
		String destFile = pszDest;

		IStream* pkIStream = CreateFileReader(pszSrc);
		if (!pkIStream) {
			eResult = COPY_READ_FAIL;
		}
		else {
			int nSize = pkIStream->GetSize();
			OStream* pkOStream = CreateFileWriter(pszDest, false);
			if (!pkOStream) {
				eResult = COPY_WRITE_FAIL;
			}
			else {

				int nPercent = 0, nNewPercent = 0;
				byte buffer[32768];
				for (int nTotal = 0; nTotal < nSize; nTotal += sizeof(buffer)) {
					int nCount = Mathi::Min(nSize - nTotal, sizeof(buffer));
					pkIStream->Read(buffer, nCount);
					if (pkIStream->IsError()) {
						eResult = COPY_READ_FAIL;
					}

					pkOStream->Write(buffer, nCount);
					if (pkOStream->IsError())
					{
						eResult = COPY_WRITE_FAIL;
					}

					nNewPercent = nTotal * 100 / nSize;
					if (pkProgress && nPercent != nNewPercent && !pkProgress->Poll((f32)nNewPercent / 100.0f)) {
						eResult = COPY_CANCEL;
					}
					nPercent = nNewPercent;
				}

				if (eResult ==  COPY_OK)
					if (!pkOStream->Close())
						eResult = COPY_WRITE_FAIL;
				EP3DDelete pkOStream;
			}

			if (eResult == COPY_OK)
				if (pkIStream->Close())
					eResult =  COPY_READ_FAIL;
			EP3DDelete pkIStream;
		}
		if (pkProgress && eResult == COPY_OK && !pkProgress->Poll(1.0f)) {
			eResult = COPY_CANCEL;
		}
		return eResult;
	}

	void FileSystem::FindFiles(Array<String>& Result, const TCHAR* FileName, bool Files, bool Directories)
	{
#if UNICODE
		_wfinddata_t Found;
		long lFound = (long)_wfindfirst(FileName, &Found);
		if (-1 != lFound) {
			do {
				if ((wcscmp(Found.name, L".") != 0) &&
					(wcscmp(Found.name, L"..") != 0) &&
					((Found.attrib & _A_SUBDIR) ? Directories : Files)) {
						Result.Add(Found.name);
				}
			} while (_wfindnext(lFound, &Found) != -1);
		}
		_findclose(lFound);
#else
		_finddata_t Found;
		long lFound = (long)_findfirst(FileName, &Found);
		if (-1 != lFound) {
			do {
				if ((strcmp(Found.name, ".") != 0) &&
					(strcmp(Found.name, "..") != 0) &&
					((Found.attrib & _A_SUBDIR) ? Directories : Files)) {
						Result.Add(Found.name);
				}
			} while (_findnext(lFound, &Found) != -1);
		}
		_findclose(lFound);
#endif
	}

	String& FileSystem::DeletePathFromFilename(String& filename)
	{
		int nPos = filename.ReverseFind(TEXT('/'));
		if (nPos > -1 && nPos != filename.GetLength() - 1) {
			filename = filename.Right(filename.GetLength() - nPos);
		}
		return filename;
	}

	XMLWriter* FileSystem::CreateXMLFileWriter(const TCHAR* pszFilename, bool bAppend)
	{
		OStream* pkStream = CreateFileWriter(pszFilename, bAppend);
		if (!pkStream) {
			LogError(TEXT("failed to write file: %s"), pszFilename);
			return NULL;
		}

		XMLWriter* pkWriter = EP3DNew XMLWriter(pkStream);
		if (!pkWriter) {
			LogError(TEXT("failed to Create xml writer"));
			return NULL;
		}
		return pkWriter;
	}
}

